package com.yl.immodule.adapter;

import com.android.yl.ylicpsdk.ICPRtcManager;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.unionbroad.greendao.User;
import com.yl.immodule.R;
import com.yl.immodule.databinding.ItemUserBinding;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ContactsAdapter extends ListAdapter<User, ContactsAdapter.ContactViewHolder> {
        private final String TAG = ContactsAdapter.class.getSimpleName();
    private final ContactClickListener listener;
    private final Set<User> selectedUsers = new HashSet<>();
    
    public ContactsAdapter(ContactClickListener listener) {
        super(new UserDiffCallback());
        this.listener = listener;
    }
    
    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemUserBinding binding = ItemUserBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ContactViewHolder(binding);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
        User user = getItem(position);
        boolean isSelected = selectedUsers.contains(user);
        holder.bind(user, isSelected,ICPRtcManager.getsInstance().getCurrentUser() == null? false : ICPRtcManager.getsInstance().getCurrentUser().getNumber() == user.getNumber(),listener);
    }
    
    @Override
    public void submitList(List<User> list) {
        // 确保传递新的列表实例给父类方法
        super.submitList(list != null ? new ArrayList<>(list) : null);
    }
    
    public void toggleSelection(User user) {
        if (selectedUsers.contains(user)) {
            selectedUsers.remove(user);
        } else {
            selectedUsers.add(user);
        }
        notifyDataSetChanged(); // 强制刷新UI，因为选中状态改变
    }
    
    public void clearSelection() {
        selectedUsers.clear();
        notifyDataSetChanged();
    }
    
    public Set<User> getSelectedUsers() {
        return new HashSet<>(selectedUsers);
    }
    
    public int getLastSelectedPosition() {
        // 如果没有选中的用户，返回-1
        if (selectedUsers == null || selectedUsers.isEmpty()) {
            return -1;
        }
        
        // 获取当前数据列表
        List<User> currentList = getCurrentList();
        if (currentList == null || currentList.isEmpty()) {
            return -1;
        }
        
        // 从后向前遍历查找选中的item
        for (int i = currentList.size() - 1; i >= 0; i--) {
            User user = currentList.get(i);
            if (selectedUsers.contains(user)) {
                return i;
            }
        }
        
        return -1;
    }
    
    public static class ContactViewHolder extends RecyclerView.ViewHolder {
        private final ItemUserBinding binding;
        
        public ContactViewHolder(ItemUserBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
        
        public void bind(final User user, boolean isSelected, boolean isCheckGone, final ContactClickListener listener) {
            if (user == null) {
                return;
            }
            binding.setUser(user);
            binding.setIsSelected(isSelected);
            binding.setIsCheckGone(isCheckGone);
            if (user.getStatus() == 1) {
                binding.userIcon.setImageResource(user.getType().equals("dispatch")?R.drawable.ic_diapatch_online:R.drawable.ic_user_online);
            } else {
                binding.userIcon.setImageResource(user.getType().equals("dispatch")?R.drawable.ic_diapatch_offline:R.drawable.ic_user_offline);
            }
            binding.getRoot().setOnClickListener(v -> {
                if (listener != null) {
                    listener.onContactClick(user);
                }
            });
            binding.executePendingBindings();
        }
    }
    
    private static class UserDiffCallback extends DiffUtil.ItemCallback<User> {
        @Override
        public boolean areItemsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            // 只对比用户ID是否相同
            return oldItem.getNumber() == newItem.getNumber();
        }
        
        @Override
        public boolean areContentsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            // 简化比较逻辑，只考虑关键属性
            if (oldItem.getStatus() != newItem.getStatus()) {
                return false;
            }
            
            String oldName = oldItem.getName();
            String newName = newItem.getName();
            boolean nameEquals = (oldName == null && newName == null) || 
                               (oldName != null && newName != null && oldName.equals(newName));
                               
            if (!nameEquals) {
                return false;
            }
            
            return true;
        }
    }
    
    public interface ContactClickListener {
        void onContactClick(User user);
    }
} 